/**
 * 
 */
package net.betou.trade.main.manager.impl;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import net.betou.common.hibernate3.Updater;
import net.betou.core.entity.ConfigLogin;
import net.betou.trade.entity.main.Role;
import net.betou.trade.entity.main.RoleExt;
import net.betou.trade.main.dao.RoleExtDao;
import net.betou.trade.main.manager.RoleExtMng;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 叶装装
 * 
 */
@Service
@Transactional
public class RoleExtMngImpl implements RoleExtMng{

	public RoleExt deleteById( Integer id ) {
		return dao.deleteById( id );
	}

	@Transactional( readOnly = true )
	public RoleExt findById( Integer id ) {
		return dao.findById( id );
	}

	@Transactional( readOnly = true )
	public RoleExt findByKey( String key ) {
		return dao.findByKey( key );
	}

	@Transactional( readOnly = true )
	public List< RoleExt > getList( Integer roleId ) {
		return dao.getList( roleId );
	}

	public RoleExt save( RoleExt bean, Role role ) {
		bean.setRole( role );
		return dao.save( bean );
	}

	public RoleExt update( RoleExt roleExt ) {

		Updater< RoleExt > updater = new Updater< RoleExt >( roleExt );
		updater.include( "findDeep" );
		updater.include( "deleteDeep" );
		updater.include( "updateDeep" );
		updater.include( "viewRoles" );
		roleExt = dao.updateByUpdater( updater );

		return roleExt;
	}

	public Set< RoleExt > init( Role role ) {
		Set< RoleExt > roleSet = role.getRoleExt( );

		if( roleSet == null ){
			roleSet = new HashSet< RoleExt >( );
		}

		Set< Entry< String, String >> entrySet = ConfigLogin.roleExtMap.entrySet( );
		Iterator< Entry< String, String >> it = entrySet.iterator( );

		while( it.hasNext( ) ){
			Entry< String, String > entry = it.next( );
			if( !haveKey( roleSet, entry.getKey( ) ) ){
				RoleExt ext = new RoleExt( );

				ext.setKey( entry.getKey( ) );
				ext.setDescription( entry.getValue( ) );
				ext.init( );

				ext = save( ext, role );
				roleSet.add( ext );
			}
		}

		role.setRoleExt( roleSet );

		return roleSet;

	}

	private boolean haveKey( Set< RoleExt > roleSet, String key ) {
		for ( RoleExt re : roleSet ){
			if( re.getKey( ).compareTo( key ) == 0 ){
				return true;
			}
		}
		return false;
	}

	@Autowired
	private RoleExtDao dao;

}
